Array.prototype.remove = function (val) {
    var index = this.indexOf(val);
    if (index > -1) {
        this.splice(index, 1);
    }
};

/*设置cookie*/
function setCookie(name, value, hour) {
    var exp = new Date();
    exp.setTime(exp.getTime() + (hour || 24) * 60 * 60 * 1000);
    if (hour == -1) {
        document.cookie = name + "=" + escape(value) + ";expires=-1" + ';path=/';
    } else {
        document.cookie = name + "=" + escape(value) + ";expires=" + exp.toGMTString() + ';path=/';
    }

}

/*读取cookie*/
function getCookie(name) {
    var arr = document.cookie.match(new RegExp("(^| )" + name + "=([^;]*)(;|$)"));
    if (arr != null) return unescape(arr[2]);
    return null;
}

/**删除cookies **/
function delCookie(name) {
    setCookie(name, "", -1); 
}

/**日期转时间戳 **/
function timeToTimestamp(string) {
    var date = new Date(string);
    return date.getTime(); //13位时间戳
}

/**时间戳转日期 **/
function timestampToTime(timestamp) {
    var date = new Date(timestamp); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
    var Y = date.getFullYear() + '-';
    var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
    var D = date.getDate() + ' ';
    var h = date.getHours() + ':';
    var m = date.getMinutes() + ':';
    var s = date.getSeconds();
    return Y + M + D + h + m + s;
}

/**时间戳转日期中文 **/
function timestampToTimeZh(timestamp) {
    var date = new Date(timestamp); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
    var Y = date.getFullYear() + '年';
    var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '月';
    var D = date.getDate() + '日 ';
    var h = date.getHours() + '点';
    var m = date.getMinutes() + '分';
    var s = date.getSeconds() + '秒';
    return Y + M + D + h + m + s;
}

/**时间戳转日期 **/
function timestampToDate(timestamp) {
    var date = new Date(timestamp); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
    var Y = date.getFullYear() + '-';
    var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
    var D = date.getDate() + ' ';
    return Y + M + D;
}

function timeTransforCountdown(timestamp) {
    //计算天
    var day = Math.floor(timestamp / (1000 * 60 * 60 * 24));
    var surplus = timestamp % (1000 * 60 * 60 * 24);
    var hour = Math.floor(surplus / (1000 * 60 * 60));
    surplus = surplus % (1000 * 60 * 60);
    var minute = Math.floor(surplus / (1000 * 60));
    surplus = surplus % (1000 * 60);
    var second = Math.floor(surplus / (1000));
    return {
        day: day,
        hour: hour,
        minute: minute,
        second: second
    };
}

function Countdown(timestamp, node) {
    window.setInterval(function () {
        if (timestamp > 0) {
            var datetime = timeTransforCountdown(timestamp);
            var showContent = (datetime.day ? datetime.day + '天' : '') + (datetime.hour ? datetime.hour + '时' : '') + (datetime.minute ? datetime.minute + '分' : '') +
                (datetime.second ? datetime.second + '秒' : '');
            timestamp = timestamp - 1000;
            node.text(showContent);
        } else {
            node.text('该藏品已截拍！');
        }
    }, 1000);
}

function isInteger(obj) {
    return Math.round(obj) === obj; //是整数，则返回true，否则返回false
}

function addChatRecord(record) {
    /**
     * record {
     *  type:1文本,2图片,
     *  sourceMsg:文本内容
     *  url:图片地址,
     *  sender:发送者,
     *  accepter:接收者,
     *  isSender:是否是发送者 1.我是发送者 0.我是接收者
     * }
     */
    var chater = '';
    if (record.isSender == 1) {
        chater = record.accepter;
    } else if (record.isSender == 0) {
        chater = record.sender;
        $.noti({
            title: record.accepterName,
            text: record.sourceMsg.indexOf('product:::') != -1 ? '[藏品]' : record.sourceMsg,
            media: record.photo ? "<img src='" + record.photo + "' />" : "<img src='img/gudianhuaping.png' />",
            data: {
                message: record.sender
            },
            time: 6000,
            onClick: function (data) {
                visitUrl('/chat?charToUser=' + data.message);
            }
        });
    }
    if (!isExistChater(chater)) {
        addChater(chater, {
            nickName: record.nickName,
            photo: record.photo
        });
    }
    addChaterRecord(chater, record);
}

function getChaterList() {
    var chaterListStr = window.localStorage.getItem('chaterList');
    var chaterList = [];
    if (chaterListStr) {
        chaterList = JSON.parse(chaterListStr);
    } else {
        window.localStorage.setItem('chaterList', JSON.stringify(chaterList));
    }
    return chaterList;
}

//查看我的所有聊天信息
function getChatList() {
    var chaterList = getChaterList();
    var chats = [];
    for (var i = 0; i < chaterList.length; i++) {
        var chat = {};
        chat.name = chaterList[i];
        chat.list = JSON.parse(window.localStorage.getItem('_' + chat.name));
        chat.noReadCount = 0;
        var userInfo = JSON.parse(window.localStorage.getItem('_' + chat.name + '_info'));
        chat.nickName = userInfo.nickName;
        chat.photo = userInfo.photo;
        for (var j = 0; j < chat.list.length; j++) {
            if (chat.list[j].isRead == 0) {
                chat.noReadCount = chat.noReadCount + 1;
            }
        }
        chats.push(chat);
    }
    return chats;
}

function getNoReadCount() {
    var chaterList = getChaterList();
    var noReadCount = 0;
    for (var i = 0; i < chaterList.length; i++) {
        var chat = {};
        chat.name = chaterList[i];
        chat.list = JSON.parse(window.localStorage.getItem('_' + chat.name));
        for (var j = 0; j < chat.list.length; j++) {
            if (chat.list[j].isRead == 0) {
                noReadCount++;
            }
        }
    }
    return noReadCount;
}

/**
 * 查看聊天者是否存在
 * @param {*} chater 
 */
function isExistChater(chater) {
    var chaterList = getChaterList();
    for (var i = 0; i < chaterList.length; i++) {
        if (chaterList[i] == chater)
            return chaterList[i];
    }
    return false;
}

/**
 * 添加一个聊天者
 */
function addChater(chater, userInfo) {
    var chaterList = getChaterList();
    var chatContentList = [];
    chaterList.push(chater);
    window.localStorage.setItem('chaterList', JSON.stringify(chaterList));
    window.localStorage.setItem('_' + chater, JSON.stringify(chatContentList));
    window.localStorage.setItem('_' + chater + '_info', JSON.stringify(userInfo));
}

/**
 * 增加一个聊天者的对话记录
 */
function addChaterRecord(chater, record) {
    var chatContentListStr = window.localStorage.getItem('_' + chater);
    var chatContentList = [];
    if (chatContentListStr)
        chatContentList = JSON.parse(chatContentListStr);
    chatContentList.push(record);
    window.localStorage.setItem('_' + chater, JSON.stringify(chatContentList));
}

/**
 * 删除一个聊天者的对话记录
 */
function delChater(chater) {
    var chaterList = getChaterList();
    //删除该用户的保存信息
    chaterList.remove(chater);
    window.localStorage.setItem('chaterList', JSON.stringify(chaterList));
    window.localStorage.removeItem('_' + chater);
    window.localStorage.removeItem('_' + chater + '_info');
    return false;
}

/**
 * 取得我的所有未读信息的数量
 */
function getMyUnReadRecord() {
    var chaterList = getChaterList();
    var unReadCount = 0;
    for (var i = 0; i < chaterList.length; i++) {
        var chat = {};
        chat.name = chaterList[i];
        chat.list = JSON.parse(window.localStorage.getItem('_' + chat.name));
        for (var j = 0; j < chat.list.length; j++) {
            if (chat.list[j].isRead == 0) {
                unReadCount++;
            }
        }
    }
    return unReadCount;
}

/**
 * 读取一个聊天者的所有信息
 */
function readChaterAllRecord(chater) {
    var chatContentListStr = window.localStorage.getItem('_' + chater);
    var chatContentList = [];
    if (chatContentListStr)
        chatContentList = JSON.parse(chatContentListStr);
    for (var i = 0; i < chatContentList.length; i++) {
        chatContentList[i].isRead = 1;
    }
    window.localStorage.setItem('_' + chater, JSON.stringify(chatContentList));
}

/**
 * 取得一个聊天者的所有信息
 */
function getChaterAllRecord(chater) {
    var chatContentListStr = window.localStorage.getItem('_' + chater);
    var chatContentList = [];
    if (chatContentListStr)
        chatContentList = JSON.parse(chatContentListStr);
    return chatContentList;
}

/* 
file 上传的文件
fileWidth 处理图片的宽度
success 上传图片成功操作
error  万一出错了，这里可以捕捉到错误信息 而且以上的then都不会执行
always 不管是成功失败，这里都会执行
需引入lrz插件
*/
/* global lrz*/
function handlePic(file, fileWidth, success, error, always) {
    lrz(file, {
            width: fileWidth || 2160,
            quality: 0.9
        })
        .then(function (rst) {
            // 这里该上传给后端啦
            /* ==================================================== */
            // 原生ajax上传代码，所以看起来特别多，但绝对能用
            // 其他框架，例如jQuery处理formData略有不同，请自行google，baidu。
            // rst.formData.append("file",rst.file);
            rst.formData.append("token", getCookie('token'));
            $.ajax({
                type: 'POST',
                url: "/antique/upload",
                data: rst.formData,
                processData: false,
                contentType: false,
                dataType: "json",
                timeout: 1000 * 30, //超时时间设置，单位毫秒
                enctype: 'multipart/form-data',
                success: success
            });
        })
        .catch(error)
        .always(always);
}

/* 
不带上传服务器版上传
file 上传的文件
fileWidth 处理图片的宽度
success 上传图片成功操作
error  万一出错了，这里可以捕捉到错误信息 而且以上的then都不会执行
always 不管是成功失败，这里都会执行
需引入lrz插件
*/
/* global lrz*/
function handlePicNoNet(file, fileWidth, success, error, always) {
    lrz(file, {
            width: fileWidth || 600
        })
        .then(function (rst) {
            console.log(rst);
            success(rst);
        })
        .catch(error)
        .always(always);
}

/*
    判断是否小程序环境 是返回true
    需引入微信js
*/
/* global navigator wx*/
function isMiniProgram() {
    var ua = navigator.userAgent.toLowerCase();
    var envType = '#';
    if (ua.match(/MicroMessenger/i) == 'micromessenger') { //微信环境
        wx.miniProgram.getEnv(function (res) {
            if (res.miniprogram) { // 小程序环境下逻辑
                envType = true;
            } else { //非小程序环境下逻辑
                envType = false;
            }
        });
    } else { //非微信环境逻辑
        envType = false;
    }
    return envType;
}
/**
 * 当前日期及前后的日期
 * @param {*} n 
 * n为你要传入的参数，当前为0，前一天为-1，后一天为1
 */
function getBeforeDate(n) { //
    var date = new Date();
    var year, month, day;
    date.setDate(date.getDate() + n);
    year = date.getFullYear();
    month = date.getMonth() + 1;
    day = date.getDate();
    s = year + '-' + (month < 10 ? ('0' + month) : month) + '-' + (day < 10 ? ('0' + day) : day);
    return s;
}

/**
 * 支付缴纳千分之6的交易费
 */
function servicePay(money) {
    money = money * (1 + 6 / 1000);
    return money.toFixed(2);
}

/**
 * 访问A标签方法  不会关闭当前小程序窗体
 */
function visitUrl(url, isWxNewOpen) {
    if (isWxNewOpen && isMiniProgram()) {
        wx.miniProgram.navigateTo({
            url: "/pages" + url
        });
    } else {
        window.location.replace(url);
    }
}
/**
 * 访问A标签方法 关闭当前小程序窗体
 */
function visitRedirectUrl(url, isWxNewOpen) {
    if (isWxNewOpen && isMiniProgram()) {
        wx.miniProgram.redirectTo ({
            url: "/pages" + url
        });
    } else {
        window.location.replace(url);
    }
}

function goWeiPay(appId, nonceStr, prepay_id, mch_id) {
    if (typeof WeixinJSBridge == "undefined") {
        if (document.addEventListener) {
            document.addEventListener('WeixinJSBridgeReady',
                onBridgeReady, false);
        } else if (document.attachEvent) {
            document.attachEvent('WeixinJSBridgeReady',
                onBridgeReady);
            document.attachEvent('onWeixinJSBridgeReady',
                onBridgeReady);
        }
    } else {
        onBridgeReady();
    }

    /* global WeixinJSBridge hex_md5*/
    function onBridgeReady() {
        var timestamp = new Date().getTime();
        var stringA = "appId=" + appId + "&nonceStr=" + nonceStr + ("&package=" + "prepay_id=" + prepay_id) + "&signType=MD5" + "&timeStamp=" + String(timestamp);
        var stringSignTemp = stringA + "&key=5dce71ee90ab4b1385bb93ee185a0113";
        var paySign = hex_md5(stringSignTemp).toUpperCase();
        WeixinJSBridge.invoke(
            'getBrandWCPayRequest', {
                "appId": appId, //公众号名称，由商户传入     
                "timeStamp": String(timestamp), //时间戳，自1970年以来的秒数     
                "nonceStr": nonceStr, //随机串     
                "package": "prepay_id=" + prepay_id,
                "signType": "MD5", //微信签名方式：     
                "paySign": paySign //微信签名 
            },
            function (res) {
                if (res.err_msg == "get_brand_wcpay_request:ok") {
                    console.log('支付成功');
                    //支付成功后跳转的页面
                    $.toast('支付成功!');
                    window.location.reload();
                } else if (res.err_msg == "get_brand_wcpay_request:cancel") {
                    console.log('支付取消');
                } else if (res.err_msg == "get_brand_wcpay_request:fail") {
                    console.log('支付失败');
                    WeixinJSBridge.call('closeWindow');
                } //使用以上方式判断前端返回,微信团队郑重提示：res.err_msg将在用户支付成功后返回ok,但并不保证它绝对可靠。
            }
        );
    }
}
/**
 * return 是否有支付密码
 * 成功回调
 */
function havePayPwd(successCalBack){
    $.post('/antique/api/sysUser/query_my_wallet', { token:getCookie('token')}, function (result) {
        var havePwd = false;
        if (result.code == 0 && result.data) {
            if(result.data.hasPayPass){
                successCalBack(true);
            }else{
                successCalBack(false);
            }
        } else {
            $.toast(result.message, "cancel");
        }
        return havePwd;
    });
}

/**
 * 检查该用户是不是自己
 */
function checkUserMe(userId){
    if(userId == 'hx_' + getCookie('userId')){
        return true;
    } else {
        return false;
    }
}